# coding=utf-8
"""
Created on 2015年5月27日
"""
import time
from setting_base.setting import C
from alivedb_base.nosql.redis_engine import RedisEngine
# from alivedb_base.nosql.mongo_sdk import MongoTest

from alivedb_base.rdbs.renderer_info import RendererInfo
from alivedb_base.rdbs.alive_cms import AliveCms


class BaseProcessor(object):
    """
    classdocs
    """

    def __init__(self, handler):
        '''
        Constructor
        '''
        
        self.handler = handler
        self.application = handler.application
        self.params = handler.params
        self.cmdid = handler.cmdid
        self.userid = handler.userid
        self.user_key = handler.user_key
        self.session_id = handler.session_id
        self.timestamp = handler.timestamp
        self.language = handler.language
        self.app_version = handler.app_version

        # 当前时间戳(秒)
        self.NTIME_MILL = int(time.time() * 1000)
        self.NTIME = self.NTIME_MILL / 1000
        
        # logger
        self.tracker = handler.tracker
        self.sys_logger = handler.sys_logger
        
        # db
        self.db_conns = self.application.db_conns

        self.db_pool = set()
        
        self.session_pool = set()

    def get_connections(self):
        '''
        获取连接
        '''
        
        if self.db_pool:
            return

        # 不同数据库的redis引擎, 因为redis的python库没有select方法
        self.redis_engines = dict()
        for i in C("DATABASE")["REDIS_DBS"]:
            self.redis_engines[i] = RedisEngine(self.db_conns['redis_read_%s' % i],
                                                self.db_conns['redis_write_%s' % i])
        # # redis默认库的引擎
        # self.redis_engine = self.redis_engines[C('DATABASE')["REDIS_DEFAULT_DB"]]
        
        mongo_db_names = self.application.mongo_db_names
        if 'renderer_info_read' in self.db_conns:
            self.renderer_infodb = self._get_db(RendererInfo)

        if 'alive_cms_read' in self.db_conns:
            self.alive_cmsdb = self._get_db(AliveCms)

        if 'mongo_help' in mongo_db_names:
            pass
            # self.mongo_sdk = self._get_mongo_db(MongoTest, is_default_mongo=False)

    def _get_mongo_db(self, db_cls, is_default_mongo = True):
        '''
        mongo 连接
        '''
        if is_default_mongo:
            rp, wp = self.db_conns['mongo_read'], self.db_conns['mongo_write']
        else:
            rp, wp = self.db_conns['mongo_%s_read' % (db_cls.database)], self.db_conns['mongo_%s_write' % (db_cls.database)]
        return db_cls(rp, wp)
        
    def _get_db(self, db_cls):
        '''
        mysql连接
        '''
        
        rp, wp = self.db_conns['%s_read' % (db_cls.database)], self.db_conns['%s_write' % (db_cls.database)]
        
        if getattr(self.handler.application, 'use_pooled_db', True):
            rc, wc = rp.get_connection(), wp.get_connection()
            db = db_cls(rc, wc)
            self.db_pool.add((rp, rc))
            self.db_pool.add((wp, wc))
            
            return db
        else:
            return db_cls(rp, wp)
    
    def return_connections(self):
        '''
        '''
        
        for pool, conn in self.db_pool:
            pool.return_connection(conn)
            
        self.db_pool = set()
        
        for session in self.session_pool:
            session.remove()
        self.session_pool = set()
        
#     def __del__(self):
#         pass
        
    def __getstate__(self):
        '''
        to be pickled
        '''
        
        return {}
    def _verify_params(self):
        '''
        to be override if needed
        '''
        
        
        
